#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>

#if !defined(LINUX)
#pragma warning(disable:4996)
#define snprintf _snprintf
#endif

#include "Logging.h"
#include "ConfigFile.h"
#include "ArrayList.h"
#include "TcpServerClient.h"

char           dbServer[40];                     // 数据库访问地址
char           dbUser[40];                       // 数据库访问用户
char           dbPass[40];                       // 数据库访问密码
char           dbName[40];                       // 数据库名称
unsigned short dbPort;                           // 数据库访问端口

unsigned short tcpServerPort;                    // TCP接口服务访问端口
unsigned int   heartbeatInterval;                // 客户端心跳间隔时间
unsigned int   heartbeatLostCount;               // 客户端心跳漏包判断掉线阀值

unsigned int   isSamename;                       // 客户端是否允许重名登录
char           accessUser[300];                  // 客户端访问用户设置
char           accessPass[300];                  // 客户端访问密码设置

char           curDirectory[1024];               // 当前数据保存路径
char           curDataDirectory[30];             // 当前数据保存子目录

unsigned short matchId;                          // 比赛Id
char           matchName[50];                    // 比赛名
unsigned short isInMatch;                        // 是否在比赛中，0：非比赛，1：比赛中
unsigned int   recSec;                           // 每隔多少微秒写入一次数据库

void WriteConfig()
{
    FILE *fp;
    if( ( fp = fopen(GetConfigFile(),"w") ) == NULL )
    {
        return;
    }

    fprintf(fp,"# GPS跟踪系统配置文件 Version %s \n\n",GetAppVersion());

    fprintf(fp,"#  网络使用网卡的选择\n");
	fprintf(fp,"LOGIPNUM = %d\n\n",GetLogIpNum());

    fprintf(fp,"#  日志显示细节 ：0 显示致命错误  1 显示错误  2 显示警告错误  3 显示常规日志  4 显示调试信息\n");
    fprintf(fp,"#  显示调试信息的时候，错误会出现警告窗口，不建议正式系统应用。正式系统建议设置不大于3的值\n");
	fprintf(fp,"LOGLEVEL = %d\n",GetLogLevel());
    fprintf(fp,"#  日志显示的目标 ：1 屏幕  2 文件  4 接口 ， 同时显示，取和\n");
	fprintf(fp,"LOGMODE = %d\n",GetLogMode());
    fprintf(fp,"#  是否自动清理日志以免硬盘满 ：0 不清理  1 清理\n");
	fprintf(fp,"ISDEL = %d\n",GetDelete());
    fprintf(fp,"#  日志过期的天数 ：单位是天，只有 ISDEL = 1 的时候才起作用\n");
	fprintf(fp,"DELTIME = %d\n\n",(int)(GetDeleteTime()/24/3600));

    fprintf(fp,"#  数据库访问地址\n");
    fprintf(fp,"DBSERVER = %s\n",dbServer);
    fprintf(fp,"#  数据库访问用户\n");
    fprintf(fp,"DBUSER = %s\n",dbUser);
    fprintf(fp,"#  数据库访问密码\n");
    fprintf(fp,"DBPASS = %s\n",dbPass);
    fprintf(fp,"#  数据库库名称\n");
    fprintf(fp,"DBNAME = %s\n",dbName);
    fprintf(fp,"#  数据库访问端口\n");
    fprintf(fp,"DBPORT = %u\n\n",dbPort);

    fprintf(fp,"#  TCP接口服务访问端口\n");
	fprintf(fp,"HOSTTCPPORT = %u\n\n",tcpServerPort);

	fprintf(fp,"#  客户端心跳间隔时间\n");
	fprintf(fp,"HEARTBEATINTERVAL = %u\n",heartbeatInterval);
	fprintf(fp,"#  客户端心跳漏包判断掉线阀值\n");
	fprintf(fp,"HEARTBEATLOSTCOUNT = %u\n\n",heartbeatLostCount);

    fprintf(fp,"#  客户端是否允许重名登录\n");
	fprintf(fp,"SAMENAME = %u\n\n",isSamename);

    fprintf(fp,"#  客户端访问用户设置\n");
	fprintf(fp,"USERID = %s\n",accessUser);
    fprintf(fp,"#  客户端访问密码设置\n");
	fprintf(fp,"PASSWORD = %s\n\n",accessPass);

    fprintf(fp,"#  比赛Id\n");
	fprintf(fp,"MATCHID = %u\n",matchId);
    fprintf(fp,"#  比赛名\n");
	fprintf(fp,"MATCHNAME = %s\n\n",matchName);
    fprintf(fp,"#  每隔多少微秒写入一次数据库\n");
	fprintf(fp,"RECSEC= %u\n",recSec);

	fflush(fp);
    fclose(fp);
}

void ReadConfigFile(char *file)
{
    char  czTemp[256];

    if( ReadCfgItem(file,"DBSERVER",dbServer) != 0 )
    {
        WriteFileLog(LFATAL,"Database server does not set, the program terminates.");
        exit(0);
    }
    if( ReadCfgItem(file,"DBUSER",dbUser) != 0 )
    {
        WriteFileLog(LFATAL,"Database access username does not set, the program terminates.");
        exit(0);
    }
    if( ReadCfgItem(file,"DBPASS",dbPass) != 0 )
    {
        WriteFileLog(LFATAL,"Database access password does not set, the program terminates.");
        exit(0);
    }
    if( ReadCfgItem(file,"DBNAME",dbName) != 0 )
    {
        WriteFileLog(LFATAL,"Database name does not set, the program terminates.");
        exit(0);
    }
    if( ReadCfgItem(file,"DBPORT",czTemp) != 0 )
    {
        WriteFileLog(LFATAL,"Database access port does not defined, the program terminates.");
        exit(0);
    }
    dbPort = (unsigned short)atoi(czTemp);

    if( ReadCfgItem(file,"HOSTTCPPORT",czTemp) != 0 )
    {
        WriteFileLog(LFATAL,"HOSTTCPPORT does not defined, the program terminates.");
        exit(0);
    }
    tcpServerPort = (unsigned short)atoi(czTemp);

    if( ReadCfgItem(file,"HEARTBEATINTERVAL",czTemp) != 0 )
    {
        WriteFileLog(LFATAL,"HEARTBEATINTERVAL does not defined, the program terminates.");
        exit(0);
    }
    heartbeatInterval = (unsigned int)atoi(czTemp);
    if( ReadCfgItem(file,"HEARTBEATLOSTCOUNT",czTemp) != 0 )
    {
        WriteFileLog(LFATAL,"HEARTBEATLOSTCOUNT does not defined, the program terminates.");
        exit(0);
    }
    heartbeatLostCount = (unsigned int)atoi(czTemp);

    if( ReadCfgItem(file,"SAMENAME",czTemp) != 0 )
    {
        WriteFileLog(LFATAL,"SAMENAME does not defined, the program terminates.");
        exit(0);
    }
    isSamename = (unsigned short)atoi(czTemp);
    if( ReadCfgItem(file,"USERID",accessUser) != 0 )
    {
        WriteFileLog(LFATAL,"USERID does not defined, the program terminates.");
        exit(0);
    }
    if( ReadCfgItem(file,"PASSWORD",accessPass) != 0 )
    {
        WriteFileLog(LFATAL,"PASSWORD does not defined, the program terminates.");
        exit(0);
    }

    if( ReadCfgItem(file,"MATCHID",czTemp) != 0 )
    {
        WriteFileLog(LFATAL,"MATCHID does not defined, the program terminates.");
        exit(0);
    }
    matchId= (unsigned short)atoi(czTemp);
    if( ReadCfgItem(file,"MATCHNAME",matchName) != 0 )
    {
        WriteFileLog(LFATAL,"MATCHNAME does not defined, the program terminates.");
        exit(0);
    }
    if( ReadCfgItem(file,"RECSEC",czTemp) != 0 )
    {
        WriteFileLog(LFATAL,"RECSEC does not defined, the program terminates.");
        exit(0);
    }
    recSec = (unsigned int)atoi(czTemp);

    //WriteFileLog(LHINT,"程序配置文件读取完毕。");
}

void GetDirectory()
{
	int  i,j;

	memset(curDirectory,0,sizeof(curDirectory));
    #if defined(LINUX)
	readlink ("/proc/self/exe", curDirectory, 1020);
    #else
	GetModuleFileName( NULL, curDirectory, 1020 );
    #endif
	j = strlen(curDirectory);
	for(i=j-1;i>0;i--)
	{
        #if defined(LINUX)
		if(curDirectory[i]=='/')
        #else
		if(curDirectory[i]=='\\')
        #endif
		{
			curDirectory[i]='\0';
			break;
		}
	}
}

void SetSaveDirectory()
{
	int  wYear,wMonth,wDay,wHour,wMinute,wSecond;
    time_t   timep;
    struct   tm *p;
    time(&timep);
    p = localtime(&timep);
    wYear   = p->tm_year + 1900;
    wMonth  = p->tm_mon + 1;
    wDay    = p->tm_mday;
    wHour   = p->tm_hour;
    wMinute = p->tm_min;
    wSecond = p->tm_sec;
	snprintf(curDataDirectory,30,"%04d%02d%02d%02d%02d%02d",wYear, wMonth, wDay, wHour, wMinute, wSecond);
}

